"""
运算符优先级
学习目标：
1. 理解运算符的优先级顺序
2. 掌握使用括号控制运算顺序
3. 避免因优先级产生的错误
"""

# ==================== 1. 运算符优先级概述 ====================
print("=" * 50)
print("1. 运算符优先级表（从高到低）")
print("=" * 50)

print("""
优先级（从高到低）：

1. **                  幂运算
2. ~ + -              按位取反、正号、负号（一元运算符）
3. * / // %           乘、除、整除、取余
4. + -                加、减
5. << >>              左移、右移
6. &                  按位与
7. ^                  按位异或
8. |                  按位或
9. < <= > >= == !=    比较运算符
10. is, is not        身份运算符
11. in, not in        成员运算符
12. not               逻辑非
13. and               逻辑与
14. or                逻辑或
15. =, +=, -=, 等     赋值运算符

💡 记忆技巧：
- 算术 > 比较 > 逻辑 > 赋值
- 乘除 > 加减
- not > and > or
""")

print()

# ==================== 2. 算术运算符的优先级 ====================
print("=" * 50)
print("2. 算术运算符的优先级")
print("=" * 50)

# 幂运算 > 乘除 > 加减
result = 2 + 3 * 4
print(f"2 + 3 * 4 = {result}")
print("  解析：先算 3 * 4 = 12，再算 2 + 12 = 14")

result = 2 * 3 ** 2
print(f"\n2 * 3 ** 2 = {result}")
print("  解析：先算 3 ** 2 = 9，再算 2 * 9 = 18")

result = 10 - 2 * 3
print(f"\n10 - 2 * 3 = {result}")
print("  解析：先算 2 * 3 = 6，再算 10 - 6 = 4")

result = 10 / 2 + 3
print(f"\n10 / 2 + 3 = {result}")
print("  解析：先算 10 / 2 = 5.0，再算 5.0 + 3 = 8.0")

print()

# ==================== 3. 使用括号改变优先级 ====================
print("=" * 50)
print("3. 使用括号改变优先级")
print("=" * 50)

# 不加括号
result1 = 2 + 3 * 4
print(f"2 + 3 * 4 = {result1}")

# 加括号
result2 = (2 + 3) * 4
print(f"(2 + 3) * 4 = {result2}")

print()

# 更复杂的例子
result1 = 10 - 2 * 3
result2 = (10 - 2) * 3
print(f"10 - 2 * 3 = {result1}")
print(f"(10 - 2) * 3 = {result2}")

print()

# 嵌套括号
result = ((2 + 3) * 4 - 5) ** 2
print(f"((2 + 3) * 4 - 5) ** 2 = {result}")
print("  解析：")
print("    1. 2 + 3 = 5")
print("    2. 5 * 4 = 20")
print("    3. 20 - 5 = 15")
print("    4. 15 ** 2 = 225")

print()

# ==================== 4. 比较运算符和逻辑运算符 ====================
print("=" * 50)
print("4. 比较运算符和逻辑运算符的优先级")
print("=" * 50)

# 算术 > 比较
a = 5
b = 10
result = a + 5 > b
print(f"a = {a}, b = {b}")
print(f"a + 5 > b = {result}")
print("  解析：先算 a + 5 = 10，再比较 10 > 10 = False")

print()

# 比较 > 逻辑
result = 5 > 3 and 10 < 20
print(f"5 > 3 and 10 < 20 = {result}")
print("  解析：先算比较 5 > 3 = True 和 10 < 20 = True")
print("       再算逻辑 True and True = True")

print()

# ==================== 5. 逻辑运算符的优先级 ====================
print("=" * 50)
print("5. 逻辑运算符的优先级：not > and > or")
print("=" * 50)

# not > and
result = not True and False
print(f"not True and False = {result}")
print("  解析：先算 not True = False，再算 False and False = False")

# and > or
result = True or False and False
print(f"\nTrue or False and False = {result}")
print("  解析：先算 False and False = False，再算 True or False = True")

# 使用括号改变
result1 = True or False and False
result2 = (True or False) and False
print(f"\nTrue or False and False = {result1}")
print(f"(True or False) and False = {result2}")

print()

# 复杂例子
result = not False and True or False
print(f"not False and True or False = {result}")
print("  解析：")
print("    1. not False = True")
print("    2. True and True = True")
print("    3. True or False = True")

print()

# ==================== 6. 实战案例：成绩判定 ====================
print("=" * 50)
print("6. 实战：成绩判定（注意优先级）")
print("=" * 50)

score = 75
attendance = 85

# 错误的写法（可能不是预期的逻辑）
result1 = score >= 60 and attendance >= 80 or score >= 90
print(f"分数：{score}，出勤：{attendance}")
print(f"score >= 60 and attendance >= 80 or score >= 90 = {result1}")
print("  解析：(score >= 60 and attendance >= 80) or (score >= 90)")

print()

# 使用括号明确逻辑
result2 = score >= 60 and (attendance >= 80 or score >= 90)
print(f"score >= 60 and (attendance >= 80 or score >= 90) = {result2}")
print("  含义：及格 且 (出勤良好 或 成绩优秀)")

print()

# ==================== 7. 实战案例：价格计算 ====================
print("=" * 50)
print("7. 实战：商品价格计算")
print("=" * 50)

price = 100
quantity = 3
discount = 0.9
shipping = 10

# 错误的计算（没注意优先级）
wrong_total = price * quantity * discount + shipping
print(f"价格：¥{price}，数量：{quantity}，折扣：{discount}折，运费：¥{shipping}")
print(f"错误算法：price * quantity * discount + shipping = ¥{wrong_total}")
print("  实际执行：(price * quantity * discount) + shipping")

# 正确的计算
correct_total = (price * quantity + shipping) * discount
print(f"\n正确算法：(price * quantity + shipping) * discount = ¥{correct_total}")
print("  含义：先加运费再打折")

print()

# ==================== 8. 实战案例：条件判断 ====================
print("=" * 50)
print("8. 实战：用户权限判断")
print("=" * 50)

age = 16
is_member = True
has_permission = False

# 复杂条件
result = age >= 18 and is_member or has_permission
print(f"年龄：{age}，会员：{is_member}，特殊权限：{has_permission}")
print(f"age >= 18 and is_member or has_permission = {result}")
print("  解析：(age >= 18 and is_member) or has_permission")
print("       (False and True) or False = False")

print()

# 不同的括号，不同的逻辑
result2 = age >= 18 and (is_member or has_permission)
print(f"age >= 18 and (is_member or has_permission) = {result2}")
print("  解析：age >= 18 and (True or False)")
print("       False and True = False")

print()

# ==================== 9. 位运算符的优先级 ====================
print("=" * 50)
print("9. 位运算符的优先级")
print("=" * 50)

a = 12  # 1100
b = 10  # 1010
c = 6   # 0110

# 位运算符：& > ^ > |
result = a | b & c
print(f"a = {a} (1100), b = {b} (1010), c = {c} (0110)")
print(f"a | b & c = {result}")
print(f"  解析：先算 b & c = {b & c}，再算 a | {b & c} = {result}")

# 使用括号改变
result2 = (a | b) & c
print(f"\n(a | b) & c = {result2}")
print(f"  解析：先算 a | b = {a | b}，再算 {a | b} & c = {result2}")

print()

# ==================== 10. 混合运算 ====================
print("=" * 50)
print("10. 混合运算示例")
print("=" * 50)

x = 5
y = 10

# 算术 + 比较 + 逻辑
result = x + 5 > y and y * 2 < 25 or not x == 5
print(f"x = {x}, y = {y}")
print(f"x + 5 > y and y * 2 < 25 or not x == 5 = {result}")
print("\n详细解析：")
print(f"  1. x + 5 = {x + 5}")
print(f"  2. y * 2 = {y * 2}")
print(f"  3. {x + 5} > {y} = {x + 5 > y}")
print(f"  4. {y * 2} < 25 = {y * 2 < 25}")
print(f"  5. x == 5 = {x == 5}")
print(f"  6. not {x == 5} = {not x == 5}")
print(f"  7. {x + 5 > y} and {y * 2 < 25} = {(x + 5 > y) and (y * 2 < 25)}")
print(f"  8. {(x + 5 > y) and (y * 2 < 25)} or {not x == 5} = {result}")

print()

# ==================== 11. 实战：BMI计算 ====================
print("=" * 50)
print("11. 实战：BMI计算与判定")
print("=" * 50)

height = 1.75  # 米
weight = 70    # 千克

# 计算BMI
bmi = weight / height ** 2
print(f"身高：{height}m，体重：{weight}kg")
print(f"BMI = weight / height ** 2 = {bmi:.2f}")
print("  解析：先算 height ** 2，再算除法")

print()

# BMI分类（注意优先级）
is_healthy = 18.5 <= bmi < 24 and weight > 0 and height > 0
print(f"是否健康体重：{is_healthy}")
print("  条件：18.5 <= bmi < 24 and weight > 0 and height > 0")

print()

# ==================== 12. 实战：复利计算 ====================
print("=" * 50)
print("12. 实战：复利计算")
print("=" * 50)

principal = 10000   # 本金
rate = 0.05        # 年利率
years = 3          # 年数

# 复利公式：A = P(1 + r)^n
# 注意优先级
amount = principal * (1 + rate) ** years
print(f"本金：¥{principal}，年利率：{rate * 100}%，年数：{years}")
print(f"amount = principal * (1 + rate) ** years")
print(f"到期金额：¥{amount:.2f}")
print()
print("运算顺序：")
print(f"  1. 括号内：1 + rate = {1 + rate}")
print(f"  2. 幂运算：{1 + rate} ** {years} = {(1 + rate) ** years:.6f}")
print(f"  3. 乘法：{principal} * {(1 + rate) ** years:.6f} = {amount:.2f}")

print()

# ==================== 13. 常见错误示例 ====================
print("=" * 50)
print("13. 常见优先级错误")
print("=" * 50)

print("【错误1：忽略乘法优先级】")
# 想计算：(a + b) * c
a, b, c = 2, 3, 4
wrong = a + b * c  # 实际是：a + (b * c)
right = (a + b) * c
print(f"a = {a}, b = {b}, c = {c}")
print(f"❌ a + b * c = {wrong} （实际是 a + (b * c)）")
print(f"✅ (a + b) * c = {right}")

print()

print("【错误2：忽略逻辑运算符优先级】")
# 想判断：成年 且 (是学生 或 有工作)
age = 20
is_student = False
has_job = True

# 错误写法
wrong = age >= 18 and is_student or has_job
print(f"年龄：{age}，学生：{is_student}，有工作：{has_job}")
print(f"❌ age >= 18 and is_student or has_job = {wrong}")
print("   实际是：(age >= 18 and is_student) or has_job")

# 正确写法
right = age >= 18 and (is_student or has_job)
print(f"✅ age >= 18 and (is_student or has_job) = {right}")

print()

print("【错误3：忽略比较运算符的结合性】")
x, y, z = 5, 10, 15

# 链式比较（Python特性，推荐）
result1 = x < y < z
print(f"x = {x}, y = {y}, z = {z}")
print(f"✅ x < y < z = {result1} （Python链式比较）")

# 错误理解（不要这样想）
# result2 = (x < y) < z  # True < 15 → 1 < 15 → True（会得到意外结果）

print()

# ==================== 14. 最佳实践 ====================
print("=" * 50)
print("14. 最佳实践建议")
print("=" * 50)

print("""
💡 最佳实践：

1. **遇到复杂表达式，使用括号**
   - 即使不需要括号，也可以用来增强可读性
   - (a + b) * c 比 a + b * c 更清晰

2. **分步计算复杂表达式**
   - 不要写太长的单行表达式
   - 拆分成多步，增加可读性

3. **逻辑表达式要特别注意**
   - not > and > or
   - 复杂逻辑一定要加括号

4. **不要依赖记忆，多用括号**
   - 代码是给人读的
   - 清晰 > 简洁

5. **测试边界情况**
   - 验证运算结果是否符合预期
   - 特别是条件判断
""")

print()

# ==================== 总结 ====================
print("=" * 50)
print("✨ 运算符优先级总结")
print("=" * 50)
print("""
优先级记忆口诀：

1. **括号最优先**
2. 幂运算其次（**）
3. 乘除高于加减（* / // % 高于 + -）
4. 移位和位运算（<< >> & ^ |）
5. 比较运算符（< > == !=）
6. 逻辑非最先（not）
7. 逻辑与其次（and）
8. 逻辑或最后（or）
9. 赋值运算最低（=）

💡 实用建议：
- 不确定优先级时，加括号！
- 复杂表达式分步计算
- 代码可读性第一
- 多写注释说明复杂逻辑

⚠️ 特别注意：
- and 优先于 or
- 比较运算优先于逻辑运算
- 算术运算优先于比较运算
- Python支持链式比较：a < b < c
""")
print("=" * 50)

